package lichtruong.bk.cse;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class AuToGet extends Activity implements LocationListener {

	Marker now;
	MediaPlayer myMusic;
	Circle circle;
	int leveluser;
	double[] LatLng;
	CharSequence items[];
	LatLng POINT_SHOW, POINT_CURRENT;
	GoogleMap googleMap;
	String allPointReport;
	int waring = 1;
	int[] allindex_waring, cancel;
	static double latitude, longitude, lat_old, lng_old;
	LocationManager locationManager;
	int index_waring;
	boolean center_trueorfalse = true, ring_waring = true;
	ArrayList<PR> DataReported = new ArrayList<PR>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		lat_old = 10.776126655419617;
		lng_old = 106.64446815587598;
		setContentView(R.layout.map1);
		myMusic = MediaPlayer.create(AuToGet.this, R.raw.ring);
		if (!check_locationCurrent()) {
			checkGPS();
		}
		cancel = new int[10];
		googleMap = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.map)).getMap();
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				this);

		dataPR();
		DrawAllPointReported();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.auto_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.fm:
			expansionAuto();
			break;
		case R.id.option:
			optionSelect();
			break;
		}
		return true;
	}

	private void expansionAuto() {
		items = new String[2];
		ring_waring = true;
		center_trueorfalse = true;
		items[0] = "Bỏ Chuông Báo Động";
		items[1] = "Bỏ Chế Độ Lấy Điểm Hiện Tại Làm trung Tâm";
		AlertDialog.Builder builder = new AlertDialog.Builder(AuToGet.this);
		builder.setTitle(" Các tính năng mở rộng ")
				.setMultiChoiceItems(items, null,
						new DialogInterface.OnMultiChoiceClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {
								// TODO Auto-generated method stub
								if (isChecked) {
									if(which == 0) ring_waring = false;
									else center_trueorfalse = false;
								} else {
									if(which == 0) ring_waring = true;
									else center_trueorfalse = true;
								}
							}
						})
						.setNegativeButton("Hoàn Thành",
								new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						})
						.show();
	}

	private void optionSelect() {
		String login;
		Database getlevel = new Database(AuToGet.this);
		getlevel.open();
		if (Integer.parseInt(getlevel.getData_USER().level) == 0) {
			login = "                 Đăng Nhập     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		} else {
			login = "                 Đăng Xuất     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		}
		getlevel.close();
		CharSequence[] items = { "                   Đăng Ký ", login,
				"          Báo Cáo Tắc Đường   ",
				"     Xem Các Điểm Tắc Đường  " };
		new AlertDialog.Builder(this).setTitle("   Danh Sách Lựa Chọn  ")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (which == 0) {
							Intent register = new Intent(AuToGet.this,
									Register.class);
							startActivity(register);
						} else if (which == 1) {
							if (leveluser == 0) {
								Intent login = new Intent(AuToGet.this,
										Login.class);
								login.putExtra("back", "4");
								startActivity(login);
							} else {
								Database updateLevel = new Database(
										AuToGet.this);
								updateLevel.open();
								updateLevel.updateLevelUser("0");
								updateLevel.close();
								Toast.makeText(getBaseContext(),
										"Đăng Xuất Thành Công",
										Toast.LENGTH_SHORT).show();
							}
						} else if (which == 2) {
							Intent report = new Intent(AuToGet.this,
									Report.class);
							startActivity(report);
						} else {
							Intent reported = new Intent(AuToGet.this,
									GetDataReported.class);
							startActivity(reported);
						}
					}
				}).show();
		// .setMessage(message)
	}

	public void checkGPS() {
		if (!check_locationCurrent()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(AuToGet.this);
			builder.setMessage(
					"  Bạn Phải Bật GPS Trước Khi Thực Hiện Chức Năng Báo Cáo")
					.setTitle("  Tin Nhắn Từ Blue Road  ")
					.setPositiveButton("Đồng Ý",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									checkGPS();
								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(AuToGet.this,
											menu.class);
									startActivity(menu);
								}
							}).setCancelable(false);
			builder.show();
		}
	}

	private void draw_point_goal() {
		POINT_SHOW = new LatLng(latitude, longitude);
		circle = googleMap.addCircle(new CircleOptions().center(POINT_SHOW)
				.radius(500).strokeColor(Color.RED));
		circle.setStrokeWidth(3);
	}

	// check GPS
	public boolean check_locationCurrent() {
		menu locationCurrent = new menu();
		double[] latlngCurrent = locationCurrent.locationCurrent();
		latitude = latlngCurrent[0];
		longitude = latlngCurrent[1];
		if (latitude == 10.776126655419617 && longitude == 106.64446815587598) {
			return false;
		}
		return true;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if (now != null) {
			now.remove();
			circle.remove();
		}
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		if (DistanceTwoPoint(latitude, longitude, lat_old, lng_old) > 100) {
			lat_old = latitude;
			lng_old = longitude;
			googleMap.clear();
			new GetPointReported().execute();
			// show point reported on google map
			DrawAllPointReported();
			// waring if distance current to point reported < 500
			if (Wring_()) {
				if(ring_waring){
					myMusic.start();
				}
				// index_waring DataReported
				AlertDialog.Builder builder = new AlertDialog.Builder(
						AuToGet.this);
				builder.setMessage(
						"Bạn Đang Tiến Lại Gần Điểm Tắc Đường Trong Bán Kính 500m : "
								+ "\n" + allPointReport)
						.setTitle("  Tin Nhắn Từ Blue Road ")
						.setPositiveButton("Báo Lại Sau",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										myMusic.release();
										dialog.cancel();
									}
								})
						.setNegativeButton("Bỏ Qua",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										myMusic.release();
										cancel[index_waring] = 10;
									}
								}).setCancelable(false);
				builder.show();
			}
		}

		POINT_CURRENT = new LatLng(latitude, longitude);
		now = googleMap.addMarker(new MarkerOptions()
				.position(POINT_CURRENT)
				.icon(BitmapDescriptorFactory
						.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
				.title(" Điểm Hiện Tại Của Bạn "));
		if(center_trueorfalse){
			googleMap.moveCamera(CameraUpdateFactory.newLatLng(POINT_CURRENT));
			googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
		}
		// draw
		draw_point_goal();

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}

	private double DistanceTwoPoint(double lattitude_one, double longitude_one,
			double latitude_two, double longitude_two) {
		Location locationA = new Location("");
		Location locationB = new Location("");
		locationA.setLatitude(lattitude_one);
		locationA.setLongitude(longitude_one);
		locationB.setLatitude(latitude_two);
		locationB.setLongitude(longitude_two);
		double distance = locationA.distanceTo(locationB);
		return distance;
	}

	// calculator distance location current to point reported

	public boolean Wring_() {
		int wring_point = 0;
		allPointReport = "-> ";
		allindex_waring = new int[DataReported.size()];
		for (int i = 0; i < DataReported.size(); i++) {
			allindex_waring[i] = 0;
			if (DistanceTwoPoint(latitude, longitude,
					Double.parseDouble(DataReported.get(i).lat),
					Double.parseDouble(DataReported.get(i).lng)) <= 500) {
				allindex_waring[i] = 10;
				if (wring_point == 1) {
					cancel[index_waring] = 0;
				}
				index_waring = i;
				wring_point = wring_point + 1;
				if (allPointReport.length() > 10) {
					allPointReport = allPointReport + "\n" + "-> ";
				}
				allPointReport = allPointReport + DataReported.get(i).info;
			}
		}
		if (wring_point == 1) {
			if (cancel[index_waring] == 10) {
				return false;
			} else {
				return true;
			}
		} else if (wring_point > 1) {
			return true;
		} else {
			return false;
		}
	}

	public void DrawAllPointReported() {

		for (int i = 0; i < DataReported.size(); i++) {
			POINT_SHOW = new LatLng(
					Double.parseDouble(DataReported.get(i).lat),
					Double.parseDouble(DataReported.get(i).lng));
			googleMap.addMarker(new MarkerOptions()
					.position(POINT_SHOW)
					.title(DataReported.get(i).info)
					.draggable(true)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
			googleMap.addCircle(
					new CircleOptions().center(POINT_SHOW).radius(200)
							.strokeColor(Color.BLUE).fillColor(0x40ff0000))
					.setStrokeWidth(2);
		}
	}

	// get data from SQL
	public void dataPR() {
		Database getDatabaseFromSqlite = new Database(AuToGet.this);
		getDatabaseFromSqlite.open();
		DataReported = getDatabaseFromSqlite.getData_PR();
		getDatabaseFromSqlite.close();
	}

	// get data point reported
	class GetPointReported extends AsyncTask<String, String, String> {
		// get data
		JSONArray infomations_point_report;
		JSONParser JsonParser = new JSONParser();
		ArrayList<PR> informationall = new ArrayList<PR>();
		private static final String URL_GETINFO = "http://lichcse.hol.es/reported.php";

		@Override
		protected String doInBackground(String... args) {
			// Check for success tag
			int success;
			try {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("lat", String
						.valueOf(latitude)));
				params.add(new BasicNameValuePair("lng", String
						.valueOf(longitude)));
				// Posting user data to script
				JSONObject json = JsonParser.makeHttpRequest(URL_GETINFO,
						"POST", params);

				success = json.getInt("success"); // error

				if (success == 1) {

					infomations_point_report = json
							.getJSONArray("point_reported");

					for (int i = 0; i < infomations_point_report.length(); i++) {
						JSONObject l = infomations_point_report
								.getJSONObject(i);
						PR point = new PR();
						point.id = l.getString("id");
						point.info = l.getString("info");
						point.lat = l.getString("lat");
						point.lng = l.getString("lng");
						point.numpr = l.getString("numpr");
						point.timenear = l.getString("timenear");
						point.messagebl = l.getString("messagebl");
						informationall.add(point);
					}
				} else {

				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				insertPR();
			}
			return null;
		}

		public void insertPR() {
			Database insertPRDB = new Database(AuToGet.this);
			insertPRDB.open();
			insertPRDB.delete_PR();
			for (int j = 0; j < informationall.size(); j++) {
				insertPRDB.insert_PR(informationall.get(j).id,
						informationall.get(j).info, informationall.get(j).lat,
						informationall.get(j).lng, informationall.get(j).numpr,
						informationall.get(j).timenear,
						informationall.get(j).messagebl);
			}
			insertPRDB.close();
		}
	}
}
